package com.zzzs;

import java.io.*;

/**
 * @author zhu_shuai
 * @since 2021/7/18
 */
public class MyClassLoader extends ClassLoader {

    public MyClassLoader(ClassLoader parent) {
        super(parent);
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        return findClass(name);
        // try {
        //     return super.loadClass(name);
        // } catch (ClassNotFoundException e) {
        //     try {
        //         return findClass(name); // 父类加载器加载不到时，使用自定义加载器
        //     } catch (ClassNotFoundException ex) {
        //         ex.printStackTrace();
        //         return null;
        //     }
        // }
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        // byte[] data = getBytes("E:\\MyProject\\java-study\\classloader-demo\\com\\zzzs\\ATest.class");
        byte[] data = getBytes("E:\\MyProject\\java-study\\classloader-demo\\com\\zzzs\\String.class");
        Class<?> aClass = this.defineClass(name, data, 0, data.length);
        return aClass;
    }

    private static byte[] getBytes(String path){
        byte[] data = null;
        try (FileInputStream inputStream = new FileInputStream(new File(path))) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int c = 0;
            while ((c = inputStream.read()) != -1)
            {
                bos.write(c);
            }
            data = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }

    public static void main(String[] args) throws ClassNotFoundException {
        ClassLoader classLoader = MyClassLoader.class.getClassLoader();
        MyClassLoader myClassLoader = new MyClassLoader(classLoader);
        Class<?> aClass = myClassLoader.loadClass("java.lang.String");
        System.out.println(aClass.getClassLoader());
    }
}
